package com.speily.example.framework.aspectj;

import com.speily.example.common.utils.ServletUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 请求响应AOP
 * @author SPL
 * @since 2019-06-14 18:23
 */
@Aspect
@Component
@Slf4j
public class HttpAspect {

    @Pointcut("execution(public * com.speily.example.framework.web.controller.BaseController.*(..))")
    public void log2() {

    }

    /**
     * 记录请求
     */
    @Before("log2()")
    public void doBefore(JoinPoint joinPoint) {
        this.requestFilter(joinPoint);
    }

    /**
     * 响应请求
     *
     * @author jwy
     * @since 2017/12/15
     */
    @After("log2()")
    public void doAfter() {
    }

    /**
     * 打印返回值
     */
    @AfterReturning(returning = "obj",pointcut = "log2()")
    public void doAfterReturnning(Object obj) {
        log.info("响应：{}", JSONObject.toJSONString(obj));
    }

    /**
     * B、请求拦截器
     */
    private void requestFilter(JoinPoint joinPoint){

        HttpServletRequest request = ServletUtils.getRequest();

        String requestUrl = request.getRequestURI().replaceAll(request.getContextPath(), "");
        String remoteAddr = request.getRemoteAddr();
        String method = request.getMethod();
        String args = Arrays.toString(joinPoint.getArgs());

        log.info("请求地址：{}",requestUrl);
        log.info("请求源ip：{}",remoteAddr);
        log.info("请求方式：{}",method);
        log.info("请求参数：{}", args);

    }

}
